package cn.tedu.luban.settle.main.service;

import cn.tedu.luban.account.api.AccountApi;
import cn.tedu.luban.account.protocol.param.AccountPayParam;
import cn.tedu.luban.order.protocol.dto.OrderMessageDTO;
import cn.tedu.luban.settle.main.converter.SettleConverter;
import cn.tedu.luban.settle.main.repository.SettleRepository;
import cn.tedu.luban.settle.protocol.param.SettleBillParam;
import com.tedu.inn.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class SettleService {

    @Autowired
    private SettleRepository settleRepository;
    @Autowired
    private SettleConverter settleConverter;
    @Autowired
    private AccountApi accountApi;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public void settle(OrderMessageDTO orderMessageDTO) throws BusinessException {
        // 1.限产订单是否存在账单
        String orderNo = orderMessageDTO.getOrderNo();
        if(StringUtils.isEmpty(orderNo)){
            log.error("订单号为空，无法结算");
            return;
        }
        Long total = settleRepository.countSettleBillByOrderNo(orderNo);
        if(total > 0){
            throw new BusinessException("1002","账单已存在");
        }
        // 利用订单数据生成账单数据（2个账单：师傅账单、平台账单）
        List<SettleBillParam> params = settleConverter.dto2params(orderMessageDTO);
        // 第一个元素：师傅账单，第二个元素：平台账单
        settleRepository.batchSave(params);

        // 从账单中找到是师傅账单，根据结算账单数据，完成师傅打款操作
        SettleBillParam workerBill = params.get(0);
        AccountPayParam accountPayParam = new AccountPayParam();
        accountPayParam.setUserId(workerBill.getUserId());
        accountPayParam.setOrderNo(workerBill.getOrderNo());
        accountPayParam.setTotalAmount(workerBill.getTotalAmount());
        accountApi.mockPayment(accountPayParam);

        // 更改订单状态为已完成 30->40
        Message<String> message = MessageBuilder.withPayload(orderNo).build();
        rocketMQTemplate.syncSend("order-complete-topic",message);

    }
}
